// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const res = await cloud.callFunction({
    // 要调用的云函数名称
    name: 'getSignUpRecordByGameIdAndUserId',
    // 传递给云函数的参数
    data: {
      gameId: event.gameId,
      userId: event.user._id
    },
    success: res => {
      console.log("调用云函数获取用户信息成功", res)
    },
    fail: res => {
      console.log("调用云函数获取用户信息失败", res)
    }
  })
  console.log(res.result.data)
  if (res.result.data.length == 0) {
    return cloud.database().collection("signUp").add({
      data: {
        contestant_id: "",  // 考号为空
        checked: false,
        state: "未知",
        gameTitle: event.gameTitle,
        gameId: event.gameId,
        grade: event.grade,
        group: event.group,
        tutor: event.tutor,
        user: event.user,
      },
      success: res => {
        console.log("插入数据成功", res)
      },
      fail: res => {
        console.log("插入数据失败", res)
      }
    })
  } else {
    if (res.result.data[0].state == "成功") {
      // console.log("1111111")
      return res.result.data;
    }
    // console.log("2222222")
    return cloud.database().collection("signUp").where({
      gameId: event.gameId,
      "user._id": event.user._id
    }).update({
      data: {
        checked: false,
        state: "未知",
        gameTitle: event.gameTitle,
        gameId: event.gameId,
        grade: event.grade,
        group: event.group,
        tutor: event.tutor,
        user: event.user,
      },
      success: res => {
        console.log("插入数据成功", res)
      },
      fail: res => {
        console.log("插入数据失败", res)
      }
    })
  }
  
}